package com.espirit.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import com.espirit.smc.client.Client;
import com.espirit.smc.client.ClientProperties;
import com.espirit.smc.server.ServerProperties;

public final class PropertiesUtils {
	
	private PropertiesUtils(){
		
	}
	
	public static ClientProperties loadClientProperties(final String propertPath) throws IOException{
		Properties properties = new Properties();
		String path = propertPath;
		InputStream input = null;
		ClassLoader loader = Client.class.getClassLoader();
		if (StringUtils.isBlank(path)) {
			path = "client.properties";
		}
		input = loader.getResourceAsStream(path);
		if (input == null) {
			Path pp= FileSystems.getDefault().getPath(path);
			if (!Files.exists(pp)) {
				throw new RuntimeException("Can't found client.properties by path : " + propertPath);
			}
			input = new FileInputStream(pp.toFile());
		}
		properties.load(input);
		ClientProperties clientProperties = new ClientProperties();
		clientProperties.setRoot(properties.getProperty("root"));
		clientProperties.setScanPaths(properties.getProperty("scanPaths"));
		clientProperties.setTemp(properties.getProperty("tempPath"));
		clientProperties.setServerURL(properties.getProperty("serverURL"));
		clientProperties.setServerRoot(properties.getProperty("serverRoot"));
		clientProperties.setWatchPaths(properties.getProperty("watchPaths"));
		clientProperties.setIgnoreSubDirPaths(properties.getProperty("ignoreSubDirPaths"));
		clientProperties.setServerIgnoreSubDirPaths(properties.getProperty("serverIgnoreSubDirPaths"));
		return clientProperties;
	}
	
	
	public static ServerProperties loadServerProperties(final String propertPath) throws IOException{
		Properties properties = new Properties();
		String path = propertPath;
		InputStream input = null;
		ClassLoader loader = Client.class.getClassLoader();
		if (StringUtils.isBlank(path)) {
			path = "server.properties";
		}
		input = loader.getResourceAsStream(path);
		if (input == null) {
			Path pp= FileSystems.getDefault().getPath(propertPath);
			if (!Files.exists(pp)) {
				throw new RuntimeException("Can't found server.properties by path : " + propertPath);
			}
			input = new FileInputStream(pp.toFile());
		}
		properties.load(input);
		ServerProperties serverProperties = new ServerProperties();
		serverProperties.setRoot(properties.getProperty("root"));
		serverProperties.setWatchPaths(properties.getProperty("watchPaths"));
		serverProperties.setIgnoreSubDirPaths(properties.getProperty("ignoreSubDirPaths"));
		return serverProperties;
	}
}
